package com.fingard.dsp.bank.directbank.boc03;

import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.secret.salary.FieldHiddenUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

public class BOC03Base extends DirectBase {
    protected String getBnkToken(){
        if(StringHelper.isNullOrEmpty(bankFront.token)){
            if(getBankConfig().getValueAsBool("needLogin")){
                WriteBankLogLn("当前未登录前置，现在进行登录");
                login();
            }
        }
        return bankFront.token;
    }

    protected void login(){
        try{

            int tmpMaxFailCount = getBankConfig().getValueAsInt("maxLoginFail");
            if(bankFront.loginFailCount>=tmpMaxFailCount){
                WriteBankLogLn("登录失败次数"+bankFront.loginFailCount+"已达到上限，不再进行登录");
                return;
            }
            bankFront.lastLoginTime = new Date();
            bankFront.token = "";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
            xmlWriter.writeStartElementByAttr("bocb2e", "<bocb2e version=\"100\" security=\"true\" lang=\"chs\">");
            xmlWriter.writeStartElement("head");
            xmlWriter.writeElementString("termid", bankFront.termid, true);//代表一台企业前置机
            xmlWriter.writeElementString("trnid", getQryTransID());//客户端产生的报文编号
            xmlWriter.writeElementString("custid", bankFront.org);
            xmlWriter.writeElementString("cusopr", bankFront.operator);
            xmlWriter.writeElementString("trncod", "b2e0001");
            xmlWriter.writeElementString("token", "");
            xmlWriter.writeEndElement();

            xmlWriter.writeStartElement("trans");
            xmlWriter.writeStartElement("trn-b2e0001-rq");
            xmlWriter.writeStartElement("b2e0001-rq");
            xmlWriter.writeElementString("custdt", Format.DateTime14Format.format(bankFront.lastLoginTime));
            xmlWriter.writeElementString("oprpwd", bankFront.loginPasswd);
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if(tmpStrRet[0].length() == 0){
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if(tmpBkReader != null){
                    String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0001-rs/status/rspcod");
                    String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0001-rs/status/rspmsg");
                    if(tmprspcod.equals("B001")){
                        bankFront.token = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0001-rs/token");
                        bankFront.loginFailCount = 0;
                        WriteBankLogLn("登录成功");
                    }
                    else{
                        bankFront.loginFailCount=bankFront.loginFailCount+1;
                        WriteBankLogLn("登录失败：" + tmprspmsg);
                    }
                }
                else{
                    WriteBankLogLn("登录失败");
                }
            }
            else{
                WriteBankLogLn("登录失败：" + tmpStrRet[1]);
            }
        }catch(Exception e){
            WriteBankLogLn("登录异常：" + LogHelper.getStackTrace(e));
            e.printStackTrace();
        }
    }

    protected String getQryTransID(){
        Date tmpDateNow = new Date();
        return Format.Time12Format.format(tmpDateNow);
    }

    protected String getCharset(){
        return getBankConfig().getCharset("GBK");
    }

    protected void writeCommonHeader2(XmlTextWriter xmlWriter, BOC03Header p_bankHeader) throws Exception{
        if(StringHelper.isNullOrEmpty(p_bankHeader.trncod))
        {
            throw new Exception("未赋值trncod");
        }
        if(StringHelper.isNullOrEmpty(p_bankHeader.trnid))
        {
            throw new Exception("未赋值trnid");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
        xmlWriter.writeStartElementByAttr("bocb2e", "<bocb2e version=\"120\" locale=\"zh_CN\">");
        xmlWriter.writeStartElement("head");
        xmlWriter.writeElementString("termid", bankFront.termid, true);//代表一台企业前置机
        xmlWriter.writeElementString("trnid", p_bankHeader.trnid);//客户端产生的报文编号
        xmlWriter.writeElementString("custid", bankFront.org);
        xmlWriter.writeElementString("cusopr", bankFront.operator);
        xmlWriter.writeElementString("trncod", p_bankHeader.trncod);
        xmlWriter.writeElementString("token", getBnkToken());
        xmlWriter.writeEndElement();

        xmlWriter.writeStartElement("trans");
    }

    protected String[] sendToBank(String p_reqStr) throws Exception{
        String[] retStr = new String[]{"",""};

        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverURL);
        if(isNeedHiddleField) {
            WriteBankLogStep2(FieldHiddenUtil.amountHiddle(p_reqStr, new String[]{"pybamt","pydamt"}));
        }else{
            WriteBankLogStep2(p_reqStr);
        }
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/xml");
        tmpWebRequest.setRequestProperty("connection", "Close");
        String charsetName = getCharset();
        byte[] tmpToWriteBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpToWriteBytes, charsetName);
        boolean enableSalaryDecrypt = getBankConfig().getValueAsBool("enableSalaryDecrypt");
        if(enableSalaryDecrypt) {
            WriteBankLogStep3(FieldHiddenUtil.amountHiddle(retStr[1],new String[]{"pybamt","pydamt"}));
        }else{
            WriteBankLogStep3(retStr[1]);
        }
        return retStr;
    }


    protected boolean isActiveRetCode(String retCode){
        if(retCode != null){
            if(retCode.equals("B107")){//B107=TOKEN错误或未登录
                bankFront.token = "";//需要重新登录
            }
            if(retCode.equals("B001") || retCode.equals("B002") || retCode.equals("B003") || retCode.equals("B054") || retCode.equals("B500") || retCode.equals("B028")){
                bankFront.lastVisitTime = new Date();
                return true;
            }
        }
        return false;
    }
}
